<?php
namespace common\rest\actions\address;

use Yii;
use yii\base\Model;
use yii\helpers\Url;
use yii\web\ServerErrorHttpException;
use yii\rest\Action;
use common\rest\statics\ResponseDatum;
use common\rest\base\WxException;
use common\rest\statics\OperationResult;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/20
 * Time: 16:36
 */
class CreateAction extends Action{

    /**
     * @var string the scenario to be assigned to the new model before it is validated and saved.
     */
    public $scenario = Model::SCENARIO_DEFAULT;

    /**
     * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
     */
    public $viewAction = 'view';

    /**
     * auth id
     * @var string
     */
    public $authIdAttribute = "user_id";

    public function run() {
        try{
            if(!Yii::$app->user->id){
                throw new WxException(Yii::t('app.c2', "Missing parameter：{s1}", ['s1' => 'uid']), OperationResult::ERROR_600, null, []);
            }
            $model = new $this->modelClass;
            $model->{$this->authIdAttribute} = Yii::$app->user->id;
            $params = Yii::$app->getRequest()->getBodyParams();
            if($model->load($params)){
                $data = $model->save();
                if($data){
                    return ResponseDatum::getSuccessDatum(['msg' => Yii::t('app.c2', 'Operation completed successfully!')], $data);
                }else{
                    throw new WxException($model->getFirstErrorSummary(), OperationResult::ERROR_600, $params, ['errors' => $model->errors]);
                }
            }else{
                throw new WxException($model->getFirstErrorSummary(), OperationResult::ERROR_600, $params, ['errors' => $model->errors]);
            }
        }catch (WxException $ex){
            return ResponseDatum::getErrorDatum([
                'code' => (string) $ex->getCode(),
                'msg' => $ex->getMessage(),
                'extraData' => $ex->extraData,
            ], $ex->data);
        }
    }

}